package com.tusuo.stds.ui.school;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.LocationManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.view.Gravity;
import android.widget.ListView;
import android.widget.TextView;

import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.tusuo.stds.R;
import com.tusuo.stds.rest.AreaList;
import com.tusuo.stds.rest.UserInfo;
import com.tusuo.stds.ui.BaseToolbarActivity;
import com.tusuo.stds.ui.ToolbarOwner;
import com.tusuo.stds.util.Utils;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ItemClick;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.ColorRes;
import org.androidannotations.annotations.res.StringRes;
import org.parceler.Parcels;

import java.util.ArrayList;
import java.util.List;

@EActivity(R.layout.activity_province)
public class ProvinceActivity extends BaseToolbarActivity<ProvinceView, ProvincePresenter>
                                implements ProvinceView {

    @ViewById(R.id.province_tv_location)
    TextView tvLocation;

    @ViewById(R.id.list_province)
    ListView listView;

    @StringRes(R.string.toolbar_title_set_area)
    String toolbarTitle;

    @ColorRes(R.color.colorPrimary)
    int toolbarBgColor;
    @ColorRes(R.color.textColorPrimary)
    int toolbarTextColor;

    private UserInfo mUserInfo;
    private AreaList.Area mAreaFromLocation = null;

    private static final int BAIDU_LOCATION =100;
    private NormalDialog permissionDialog;

    @AfterInject
    void init() {
        mUserInfo = Parcels.unwrap(getIntent().getParcelableExtra(UserInfo.EXTRA_NAME));
    }

    @AfterViews
    void initData() {
        setupUI(this, toolbarBgColor, toolbarTextColor);

        List<ToolbarOwner.MenuAction> menuActionList = new ArrayList<>();

        ToolbarOwner.Config config = new ToolbarOwner.Config(toolbarTitle, true, R.drawable.ic_back_dark, menuActionList);
        mToolbarOwner.setConfig(config);

        LocationManager locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        if(!locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            // 未打开位置开关，可能导致定位失败或定位不准，提示用户或做相应处理
            Utils.UI.showToastLong("未打开位置开关，可能导致定位失败或定位不准");
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if(checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    || checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    ) {
                // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义)
                requestPermissions(new String[]{
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                }, BAIDU_LOCATION);

            } else {
                presenter.requestLocation();
            }
        } else {
            presenter.requestLocation();
        }
    }

    private void showDisablePermissionDialog() {
        permissionDialog = new NormalDialog(this);

        permissionDialog.isTitleShow(false)
                .btnNum(1)
                .bgColor(Color.parseColor("#FFFFFF"))
                .cornerRadius(5)
                .content("无法使用定位\n请在\"设置\"中开启定位权限")
                .contentGravity(Gravity.CENTER)
                .contentTextSize(13)
                .contentTextColor(Color.parseColor("#333333"))
                .dividerColor(Color.parseColor("#CCCCCC"))
                .btnText("确定")
                .btnTextSize(15.5f)
                .btnTextColor(Color.parseColor("#0092FF"))
                .widthScale(0.7f)
                .show();

        permissionDialog.setOnBtnClickL(new OnBtnClickL() {
            @Override
            public void onBtnClick() {
//                        IntentUtils.toSystemPermissionActivity(mActivity);
                permissionDialog.dismiss();
            }
        });

    }

    @NonNull
    @Override
    public ProvincePresenter createPresenter() {
        return new ProvincePresenter(this, mUserInfo);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        if (permissionDialog != null) {
            permissionDialog.superDismiss();
            permissionDialog = null;
        }

        super.onDestroy();
    }

    @Override public void onRequestPermissionsResult(int requestCode,String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions,grantResults);
        switch(requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case BAIDU_LOCATION:
                boolean granted = true;
                for (int i : grantResults) {
                    if (i != PackageManager.PERMISSION_GRANTED) {
                        granted = false;
                        break;
                    }
                }

                if(granted) {
                    // 获取到权限，作相应处理（调用定位SDK应当确保相关权限均被授权，否则可能引起定位失败）
                    presenter.requestLocation();
                }
                else{
                    // 没有获取到权限，做特殊处理
                    mAreaFromLocation = null;
                    tvLocation.setText("未知");
                    showDisablePermissionDialog();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void showLocation(AreaList.Area area, String location) {
        mAreaFromLocation = area;
        tvLocation.setText(location);
    }

    @UiThread
    void updateList(AreaListAdapter adapter) {
        listView.setAdapter(adapter);
    }

    @Background
    @Override
    public void setListViewAdapter(AreaListAdapter adapter) {
        while (true) {
            try {
                if (listView == null) {
                    Thread.sleep(500);
                } else {
                    updateList(adapter);
                    break;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void setArea(List<AreaList.Area> area) {
    }

    @Override
    public void setArea(List<AreaList.Area> area, int level) {
    }

    @Click(R.id.province_layout_location)
    void selectAreaFromLocation() {
        if (mAreaFromLocation != null) {
            Intent intent = new Intent();
            intent.setClass(this, AreaActivity_.class);
            intent.putExtra(UserInfo.EXTRA_NAME, Parcels.wrap(mUserInfo));

            AreaList list = new AreaList();
            list.Total = mAreaFromLocation.Children.size();
            list.Data = mAreaFromLocation.Children;
            intent.putExtra(AreaList.EXTRA_NAME, Parcels.wrap(list));

            intent.putExtra("name", mAreaFromLocation.Name);

            startActivity(intent);
        }
    }

    @ItemClick(R.id.list_province)
    void listItemClicked(AreaList.Area area) {
        if (Utils.UI.isFastDoubleClick()) {
            return;
        }
//        if (area.Children.size() > 0) {
//            setArea(area.Children, mLevel + 1);
//        }

        Intent intent = new Intent();
        intent.setClass(this, AreaActivity_.class);
        intent.putExtra(UserInfo.EXTRA_NAME, Parcels.wrap(mUserInfo));

        AreaList list = new AreaList();
        list.Total = area.Children.size();
        list.Data = area.Children;
        intent.putExtra(AreaList.EXTRA_NAME, Parcels.wrap(list));

        intent.putExtra("name", area.Name);

        startActivity(intent);
    }
}
